package com.ssm.opa.common.base.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssm.opa.common.base.exception.SysException;

import java.io.IOException;
import java.util.TimeZone;

/**
 * <p/>
 * Copyright: Copyright (c) 2016/12/9
 * <p/>
 * Company: 途牛科技有限公司华东分公司
 * <p/>
 *
 * @author wanghongqi@tuniu.com
 * @version 1.0.0
 * @project gtb-parent
 */
public class JsonUtil {

	private static final ObjectMapper objectMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).setTimeZone(TimeZone.getTimeZone("GMT+8"));

	public static <T> T parseObject(String source, Class<T> valueType) throws SysException {
		try {
			return objectMapper.readValue(source, valueType);
		} catch (IOException e) {
			throw new SysException(SysException.JSON_PARSE_EXCEPTION, e.toString());
		}
	}

	public static String toJSONString(Object source) throws SysException {
		try {
			return objectMapper.writeValueAsString(source);
		} catch (JsonProcessingException e) {
			throw new SysException(SysException.JSON_PARSE_EXCEPTION, e.toString());
		}
	}

	public static JsonNode readAsTree(String source) throws SysException {
		try {
			return objectMapper.readTree(source);
		} catch (IOException e) {
			throw new SysException(SysException.JSON_PARSE_EXCEPTION, e.toString());
		}
	}

	public static JsonNode readAsTree(byte[] source) throws SysException {
		try {
			return objectMapper.readTree(source);
		} catch (IOException e) {
			throw new SysException(SysException.JSON_PARSE_EXCEPTION, e.toString());
		}
	}

	/**
	 * 返回参数response 中 data 解析成特定的bean
	 *
	 * @param resp
	 * @param clazz
	 * @param <T>
	 * @return
	 * @throws SysException
	 */
	public static <T> T responseToBean(String resp, Class<T> clazz) throws SysException {
		JsonNode response = JsonUtil.readAsTree(resp);
		JsonNode success = response.get("success");
		if (!success.booleanValue()) {
			return null;
		}
		JsonNode data = response.get("data");
		if (data.size() == 0) {
			return null;
		}
		return JsonUtil.parseObject(data.toString(), clazz);
	}
}
